package com.ksxy.afingerprint.ui.activity

import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import com.ksxy.afingerprint.R
import com.ksxy.afingerprint.core.KeyStoreHelper
import com.ksxy.afingerprint.ui.activity.base.AbstractReturnActionActivity
import kotlinx.android.synthetic.main.activity_list_keys.*

class ListKeysActivity : AbstractReturnActionActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val keys = KeyStoreHelper.getAllKeys()?.toList()
        if(keys != null && keys.size > 0){
            viewStub.layoutResource = R.layout.activity_list_keys_list
            val listView = viewStub.inflate() as ListView
            listView.adapter = ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, keys)
            listView.onItemLongClickListener = AdapterView.OnItemLongClickListener {
                parent, view, position, id ->
                if (view is TextView){
                    val alias = view.text.toString()
                    AlertDialog.Builder(this)
                            .setMessage(String.format(getString(R.string.delete_key), alias))
                            .setPositiveButton(getString(R.string.confirm)){
                                dialog, which ->
                                if(KeyStoreHelper.deleteKey(alias)) {
                                    (listView.adapter as ArrayAdapter<String>).remove(alias)
                                }
                            }
                            .setNegativeButton(getString(R.string.cancel), null)
                            .show()
                }
                return@OnItemLongClickListener true
            }
        }else{
            viewStub.layoutResource = R.layout.activity_list_keys_text
            viewStub.inflate()
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_list_keys
    }

}

